package cn.org.mrliu.ssm.qq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.org.mrliu.ssm.qq.config.QQConfig;
import cn.org.mrliu.ssm.qq.config.QQConfigUtil;

/**
 * QQ消息处理器
 * 
 * @author MrLiu
 *
 */
public class QQMessageHandler implements Runnable {
	private static final Logger log = LoggerFactory.getLogger(QQMessageHandler.class);
	private QQConfig config = QQConfigUtil.getConfig();
	// 发送QQ消息的间隔,默认间隔2秒
	private Integer sendInterval = config.getSendInterval();
	// QQ消息拦截器
	private QQMessageInterceptor qqMessageInterceptor;

	public QQMessageHandler() {
		log.info("QQMessageHandler线程启动.....");
	}

	@Override
	public void run() {
		while (true) {
			System.out.println("while....");
			try {
				QQMessage qqMessage = QQMessageQueue.getInstance().poll();
				process(qqMessage);
				Thread.sleep(sendInterval);
			} catch (Throwable e) {
				log.error("QQMessageHandler run exception:" + e);
				e.printStackTrace();
			}
			System.out.println();
		}
	}

	public void process(QQMessage qqMessage) {
		boolean flag = true;
		try {
			if (!qqMessageInterceptor.before(qqMessage)) {
				return;
			}
			QQMessageSender.send(qqMessage);
			qqMessageInterceptor.success(qqMessage);
		} catch (Exception e) {
			flag = false;
			log.error("发送QQ消息异常:" + e);
			qqMessageInterceptor.failure(qqMessage, e);
			e.printStackTrace();
		} finally {
			qqMessageInterceptor.after(qqMessage, flag);
		}
	}

	public void setQqMessageInterceptor(QQMessageInterceptor qqMessageInterceptor) {
		this.qqMessageInterceptor = qqMessageInterceptor;
	}
}
